﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using MiniStock.BusinessLogic.EventDispatcher;
using MiniStock.BusinessLogic.EventDispatcher.MessageMap;
using MiniStock.BusinessLogic.EventQueue.Queue;
using MiniStock.Infrastructure;

namespace EventProcessorServiceHost
{
    public partial class MemoryQueueMonitoring : Form
    {
        private SynchronizationContext uiContext;
        private List<Metric> Metrics = new List<Metric>(); 

        public MemoryQueueMonitoring()
        {
            uiContext = SynchronizationContext.Current;
            InitializeComponent();
            backgroundWorker1.RunWorkerAsync();
            metricBindingSource.DataSource = Metrics;
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            base.OnClosing(e);
            backgroundWorker1.CancelAsync();
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            while (!backgroundWorker1.CancellationPending)
            {
                try
                {
                    var metrics = MemoryQueue.CollectMetrics();
                    metrics.AddRange(MessageMapHandler.CollectMetrics());

                    uiContext.Send(s =>
                                       {
                                           Metrics.Merge(metrics);
                                           metricBindingSource.DataSource = null;
                                           metricBindingSource.DataSource = Metrics;
                                       }, null);
                    Thread.Sleep(1000);
                }
                catch(Exception ex)
                {
                    Trace.TraceWarning("{0}", ex);
                }
            }
        }

        private void MemoryQueueMonitoring_Load(object sender, EventArgs e)
        {
            var desktop = Screen.GetWorkingArea(this);
            this.Location = 
                new Point(desktop.Left, desktop.Bottom - this.Height);
            this.Width = desktop.Width;
        }

        private void metricBindingSource_CurrentChanged(object sender, EventArgs e)
        {

        }
    }
}
